var socketio = {};  
var socket_io = require('socket.io');

var userList = [];
var businessList = [];

socketio.initSocketio = function(server){
    var io = socket_io(server);
    io.of('/works').on('connection', function(socket){
        console.log('socket connection')

        socket.on('open', (user) => {
            console.log(user)
            socket.email = user.email
            let isLogin = false
            for (let index = 0; index < userList.length; index++) {
                const element = userList[index];
                if (element.email === user.email) {
                    isLogin = true
                    break
                }
            }
            if (!isLogin) {
                console.log('用户列表' + userList.length)
                console.log('用户接入' + user.email)
                userList.push(user);
                console.log('用户列表' + userList.length)
            }

            // 更新当前用户，业务信息
            socket.emit('userList', userList);
            socket.emit('businessList',businessList);
            socket.broadcast.emit('userList', userList);
            socket.broadcast.emit('businessList', businessList);
        });

        socket.on('exit', function (email) {
            console.log('用户退出' + email)
            socket.broadcast.emit('userExit', email);
            userList = userList.filter(item => item.email !== email)
            console.log('用户列表' + userList.length)
        });

        socket.on('dialog', function (data) {
            console.log('dialog')
            socket.emit('dialog', data);
            // socket.broadcast.emit('dialog', data)
        });

        socket.on('disconnect', ()=>{
            console.log('连接断开' + socket.email)
            socket.broadcast.emit('userExit', socket.email);
            if (socket.businessId) {
                socket.broadcast.emit('exitEdit', {
                    id: socket.businessId,
                    email: socket.email
                });
            }
            userList = userList.filter(item => item.email !== socket.email)
            console.log('用户列表' + userList.length)
        });

        socket.on('edit', function (data) {
            console.log('用户' + data.email + '开始编辑' + data.id)
            socket.businessId = data.id
            businessList.push(data);
            socket.broadcast.emit('edit', data);
        });

        socket.on('exitEdit', function (data) {
            console.log('用户' + data.email + '退出编辑' + data.id)
            socket.broadcast.emit('exitEdit', data);
            businessList = businessList.filter(item => item.id !== data.id)
        });
    });
};  
  
module.exports = socketio; 